import noop from './noop';

/**
 * @description: 与app通信
 * @param {Function} callback
 * @return {void}
 */
function setupWebViewJavascriptBridge(callback) {
  if (window.WebViewJavascriptBridge) {
    return callback(window.WebViewJavascriptBridge);
  }
  if (window.WVJBCallbacks) {
    return window.WVJBCallbacks.push(callback);
  }
  window.WVJBCallbacks = [callback];
  const WVJBIframe = document.createElement('iframe');
  WVJBIframe.style.display = 'none';
  WVJBIframe.src = 'https://__bridge_loaded__';
  document.documentElement.appendChild(WVJBIframe);
  setTimeout(() => {
    document.documentElement.removeChild(WVJBIframe);
  }, 0);
}

/**
 * @description: 在需要调用客户端方法的组件中（事先需要与客户端同事约定好方法名）
 * @param {string} event
 * @param {any} data
 * @param {function(*) void} callback
 * @return {void}
 */
function callHandler(event, data, callback = noop) {
  setupWebViewJavascriptBridge(function (bridge) {
    bridge.callHandler(event, data, callback);
  });
}

/**
 * @description: 当客户端需要调用 js 函数时,事先注册约定好的函数即可
 * @param {string} event
 * @param {function(*,function?):void} callback
 * @return {void}
 */
function registerHandler(event, callback) {
  setupWebViewJavascriptBridge(function (bridge) {
    bridge.registerHandler(event, function (data, responseCallback) {
      callback(data, responseCallback);
    });
  });
}

const bridge = {
  callHandler,
  registerHandler,
};

export default bridge;